<template>
	<view class="page">
		<view class="tab_head">
			<view v-for="(item, index) in enableDeliveryMethod" :key="item" @click="changeTab(index)"
				class="tab_item center" :class="{ tab_item_active: tabActive === index }">{{ item }}</view>
		</view>
		<view class="tab_content">
			<view v-if="payInfo.enableDeliveryMethod===1||tabActive === 0" @click="goAddress"
				:class="{ dynamic_padding: receivingAdd ? false : true }">
				<view v-if="!receivingAdd" class="choose_receivingAdd_c" hover-class="tapstate">
					<view class="title">请选择地址</view>
					<uni-icons type="forward" size="20" color="#999"></uni-icons>
				</view>
				<view v-else class="receivingAdd_info" hover-class="tapstate">
					<view class="content">
						<view class="top">
							<text class="name">{{ receivingAdd.name }}</text>
							<text>{{ receivingAdd.tel }}</text>
						</view>
						<view class="area">
							{{
			                    receivingAdd.province +
			                    ' ' +
			                    receivingAdd.city +
			                    ' ' +
			                    receivingAdd.area +
			                    ' ' +
			                    receivingAdd.address
			                }}
						</view>
					</view>
					<uni-icons type="forward" size="20" color="#868686"></uni-icons>
				</view>
			</view>
			<view v-if="payInfo.enableDeliveryMethod===2||tabActive === 1"
				:class="{ dynamic_padding: pickAddress ? false : true }">
				<view v-if="!pickAddress" @click="goPickAddress" class="choose_receivingAdd_c" hover-class="tapstate">
					<view class="title">
						<text class="special">*</text>
						<text>请选择自提点</text>
					</view>
					<uni-icons type="forward" size="20" color="#999"></uni-icons>
				</view>
				<view v-else @click="goPickAddress" class="receivingAdd_info pick" hover-class="tapstate">
					<view class="content">
						<view class="top">
							<text class="name">{{ pickAddress.shop_name }}</text>
							<text>{{ pickAddress.shop_tel }}</text>
						</view>
						<view class="area">
							{{
			                    pickAddress.province +
			                    ' ' +
			                    pickAddress.city +
			                    ' ' +
			                    pickAddress.area +
			                    ' ' +
			                    pickAddress.shop_address
			                }}
						</view>
					</view>
					<uni-icons type="forward" size="20" color="#868686"></uni-icons>
				</view>
				<view class="input_area">
					<u--form :model="model" ref="form" errorType="message" labelWidth="auto"
						:labelStyle="{ padding: '2px 30px 2px 0',fontSize : '14px'}">
						<u-form-item prop="name" label="您的姓名" :borderBottom="true" required>
							<u--input v-model="model.name" border="none" clearable placeholder="请输入您的姓名">
							</u--input>
						</u-form-item>
						<u-form-item prop="tel" label="手机号码" required>
							<u--input v-model="model.tel" type="number" border="none" clearable placeholder="请输入您的手机号码"
								maxlength="11">
							</u--input>
						</u-form-item>
					</u--form>
				</view>
			</view>
		</view>
		<view class="goods_detail_c">
			<view class="title">商品详情</view>
			<view class="goods_item" v-for="item in payInfo.goods" :key="item.goods_id">
				<goods image_width="80px" image_height="80px" :image="imgHost + item.pic" :name="item.goods_title"
					:sub_name="item.goods_sub_title" :price="item.present_price" :num="item.buy_num"
					:price_integer="item._integer" :price_decimal="item._decimal"></goods>
			</view>
		</view>
		<view class="total_panel">
			<view class="list">
				<text class="label">合计数量</text>
				<text class="value">{{ payInfo.total_buy_num }}</text>
			</view>
			<view class="list">
				<text class="label">合计金额</text>
				<text class="value special">￥{{ payInfo.payment }}</text>
			</view>
		</view>
		<fixed-bar>
			<view class="bar_bottom">
				<view class="left">
					<text>合计：</text>
					<text class="icon special">￥</text>
					<text class="num special">{{ payInfo.payment }}</text>
				</view>
				<button @click="onSubmit" :loading="payLoading" :disabled="payLoading" :class="{ disabled: payLoading }"
					class="button" type="primary" size="mini">
					{{payLoading?'':'立即支付'}}
				</button>
			</view>
		</fixed-bar>
	</view>
	<!--支付方式选择弹出层-->
	<uni-popup ref="payMethosdPopupInstance" type="bottom" :safe-area="false">
		<view class="choose_pay_methods">
			<view class="closeable" hover-class="hover" @click="showPopup(false)">
				<uni-icons type="closeempty" size="20"></uni-icons>
			</view>
			<view class="title">请选择支付方式</view>
			<view v-for="item in payInfo.payType" :key="item" @click="onPayMethodSelect(['',2,3,'','',5][item])"
				class="item" hover-class="tapstate">{{['','微信支付','线下支付','','','余额支付'][item]}}</view>
			<view class="brace"></view>
			<view class="cancel" @click="showPopup(false)" hover-class="tapstate">取消</view>
			<view class="env"></view>
		</view>
	</uni-popup>
	<!--线下支付凭证上传弹出层-->
	<u-popup :show="showOfflineVouchersPopup" @close="showOfflineVouchersPopup=false" mode="bottom"
		overlayStyle="z-index:98;" zIndex="99" :round="10" closeable>
		<view class="offlineVouchersPopupWrap">
			<view class="title">线下支付凭证</view>
			<image :src="imgHost+payInfo.sk_pic" style="width: 100%;" mode="widthFix" @click="previewPayImg" />
			<view class="uploadWrap">
				<view class="tips">请上传支付凭证（{{offlineVouchers.length}}/1）</view>
				<u-upload :fileList="offlineVouchers" @afterRead="afterRead" @delete="deleteFile"
					:name="offlineVouchers" multiple :maxCount="1" :maxSize="5 * 1024 * 1024"
					@oversize="uploadOversize(5, $event)" :deletable="true" width="86px" height="86px">
				</u-upload>
			</view>
			<view class="button_c">
				<u-button text="提交" :color="primaryColor" shape="circle" @click="submitOfflineVouchers">
				</u-button>
			</view>
			<view class="env"></view>
		</view>
	</u-popup>
</template>

<script setup>
	import { ref, computed, reactive, nextTick } from 'vue';
	import { useCacheStore } from '@/store/modules/useCacheStore';
	import { sleep } from '@/utils/common/index';
	import request from '@/utils/common/request/index';
	// #ifdef H5
	import { wechatyPay } from '@/utils/h5/index';
	// #endif
	import { useGetThemColor } from '@/hooks/useGetThemColor';
	import { useUploadFile } from '@/hooks/useUploadFile.js';

	const { primaryColor, secondaryColor } = useGetThemColor();
	const { imgHost } = getApp().globalData;
	const cacheStore = useCacheStore();
	// * 预支付信息
	const payInfo = cacheStore.odrerStorage;

	payInfo.goods.forEach((item) => {
		[item._integer, item._decimal] = item.present_price.toString().split('.');
	});
	// * 如果预支付里有地址和自提地址信息，同步
	if (payInfo.pick_address) {
		cacheStore.setStorageData({
			data: payInfo.pick_address,
			field: 'pickAddressStorage',
		});
	}
	if (payInfo.address && !Array.isArray(payInfo.address)) {
		cacheStore.setStorageData({
			data: payInfo.address,
			field: 'addressStorage',
		});
	}

	// * 收获地址信息
	const receivingAdd = computed(() => {
		return cacheStore.addressStorage;
	});
	// * 自提地址信息
	const pickAddress = computed(() => {
		return cacheStore.pickAddressStorage;
	});

	// * tab逻辑
	let enableDeliveryMethod = [
		['快递物流', '到店自提'],
		['快递物流'],
		['到店自提']
	][payInfo.enableDeliveryMethod];
	let tabActive = ref(0);
	const changeTab = function(index) {
		tabActive.value = index;
		if (index === 1) {
			nextTick(() => {
				form.value.setRules(rules);
			})
		}
	};

	// * 前往选择收货地址
	const goAddress = () => {
		uni.navigateTo({
			url: '/pages/address/address?choose=true',
		});
	};
	// * 前往选择自提地址
	const goPickAddress = () => {
		uni.navigateTo({
			url: '/pages/self-lifting-point/self-lifting-point',
		});
	};

	// * 表单数据
	const form = ref(null);
	const model = reactive({
		name: '',
		tel: '',
	});
	const rules = {
		name: [{
				required: true,
				message: '请输入您的姓名',
				trigger: ['blur', 'change'],
			},
			{
				validator: (rule, value, callback) => {
					return value.trim() !== '';
				},
				message: '姓名格式错误',
			},
		],
		tel: [{
				required: true,
				message: '请输入手机号码',
				trigger: ['blur', 'change'],
			},
			{
				validator: (rule, value, callback) => {
					return uni.$u.test.mobile(value);
				},
				message: '手机号码格式错误',
			},
		],
	};

	// * 点击立即支付,先验证，然后弹出支付方式选择框
	const onSubmit = () => {
		if (payInfo.enableDeliveryMethod === 1 || tabActive.value === 0) {
			if (receivingAdd.value == null)
				return uni.showToast({
					title: '请选择收货地址',
					icon: 'none',
				});
			showPopup(true);
		} else if (payInfo.enableDeliveryMethod === 2 || tabActive.value === 1) {
			if (pickAddress.value == null)
				return uni.showToast({
					title: '请选择自提点',
					icon: 'none',
				});
			form.value.validate().then(() => {
				showPopup(true);
			});
		}
	};

	// * 支付方式选择
	const payMethosdPopupInstance = ref(null);
	const onPayMethodSelect = (type) => {
		showPopup(false);
		//线下支付，要弹出凭证上传框
		if (type === 3) {
			return showOfflineVouchersPopup.value = true;
		}
		handlePay(type)
	};
	const handlePay = (type) => {
		payLoading.value = true;

		let reqdata = {
			pay_type: type,
			payment: payInfo.payment,
			order_no: payInfo.order_no,
			source: 1,
		};

		reqdata.goods = payInfo.goods.map((item) => {
			return {
				goods_id: item.goods_id,
				sku_key: item.sku_key,
				buy_num: item.buy_num,
			};
		});

		if (payInfo.enableDeliveryMethod === 1 || tabActive.value === 0) {
			//邮寄
			reqdata.delivery = 1;
			reqdata.address_id = receivingAdd.value.address_id;
		} else if (payInfo.enableDeliveryMethod === 2 || tabActive.value === 1) {
			//自提
			reqdata.shr_name = model.name;
			reqdata.shr_tel = model.tel;
			reqdata.pick_id = pickAddress.value.pick_id;
			reqdata.delivery = 2;
		}

		if (type === 3) {
			reqdata.pay_img = offlineVouchers.value[0].rawUrl;
		}

		request({
				url: '/api/nyzfpay',
				method: 'POST',
				data: reqdata,
			})
		.then(async (res) => {
			if (type === 3) { //线下支付
				uni.showToast({
					title: '提交成功，审核中',
					duration: 2000,
					mask: true,
				});
				await sleep(2000);
				uni.redirectTo({
					url: '/pages/order/order?type=0',
				});
			} else if (type === 5) { //余额支付
				uni.showToast({
					title: '支付成功',
					duration: 2000,
					mask: true,
				});
				await sleep(2000);
				uni.redirectTo({
					url: '/pages/order/order?type=1',
				});

			} else if (type === 2) { //微信支付
				pay(res);
			}
		})
		.catch(() => {
			payLoading.value = false;
		});
	}

	const showPopup = (flag) => {
		flag ? payMethosdPopupInstance.value.open() : payMethosdPopupInstance.value.close();
	};

	const showOfflineVouchersPopup = ref(false);
	const offlineVouchers = ref([]);
	const { afterRead, deleteFile, uploadOversize, checkUploadSuccess } = useUploadFile();
	const submitOfflineVouchers = () => {
		if (offlineVouchers.value.length === 0) return uni.showToast({
			title: '请上传凭证',
			icon: 'none'
		})
		const isSuccess = checkUploadSuccess(offlineVouchers.value)
		if (isSuccess === false) return uni.showToast({
			title: '有图片上传中或失败',
			icon: 'none'
		})
		showOfflineVouchersPopup.value = false;
		handlePay(3)
	}
	const previewPayImg = () => {
		const img = imgHost + payInfo.sk_pic
		uni.previewImage({
			urls: [img],
			current: img
		})
	}

	// * 支付
	const payLoading = ref(false);
	const pay = (data) => {
		// #ifdef MP-WEIXIN

		// #endif

		// #ifdef H5
		wechatyPay(data, async (res) => {
			if (res.err_msg == 'get_brand_wcpay_request:ok') {
				uni.showToast({
					title: '支付成功',
					mask: true,
				});
				await sleep(800);
				return uni.redirectTo({
					url: '/pages/order/order?type=1',
				});
			}
			if (res.err_msg == 'get_brand_wcpay_request:cancel') {
				payLoading.value = false;
			}
			if (res.err_msg == 'get_brand_wcpay_request:fail') {
				uni.showToast({
					title: '支付失败',
					mask: true,
				});
				await sleep(800);
				return uni.redirectTo({
					url: '/pages/order/order?type=0',
				});
			}
		});
		// #endif
	};
</script>

<style lang="scss" scoped>
	.tab_head {
		display: flex;
		height: 40px;
		padding-top: 6px;
		overflow: hidden;

		.tab_item {
			flex: 1;
			height: 40px;
			font-size: 15px;
			background: #fff;

			&:first-child {
				border-top-left-radius: 10px;
			}

			&:last-child {
				border-top-right-radius: 10px;
			}
		}

		.tab_item_active {
			position: relative;
			top: -6px;
			padding-top: 6px;
			border-top-left-radius: 10px;
			border-top-right-radius: 10px;
			color: #fff;
			background: #c1ddd4;
		}

		.tab_item_active::after {
			content: ' ';
			position: absolute;
			bottom: 0;
			right: -10px;
			border-width: 40px 10px;
			border-style: solid;
			border-color: transparent transparent #c1ddd4 transparent;
		}

		.tab_item_active:last-child::after {
			left: -10px;
			width: 0px;
		}
	}

	.tab_content {
		border-bottom-left-radius: 10px;
		border-bottom-right-radius: 10px;
		background-color: #fff;
		overflow: hidden;
	}

	.dynamic_padding {
		padding: 10px 0;
	}

	.choose_receivingAdd_c {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 10px 10px 2px;

		.title {
			padding-left: 4px;
			color: #303133;
		}

		.special {
			color: #dd524d;
			font-size: 19px;
		}

	}

	::v-deep .uni-forms-item__label {
		padding-bottom: 0 !important;
	}

	::v-deep .uni-forms-item {
		margin-bottom: 10px !important;
	}

	.receivingAdd_info {
		display: flex;
		align-items: center;
		padding: 20px 14px;

		&.pick {
			padding: 20px 14px 10px;
		}

		.content {
			flex: 1;

			.top {
				font-weight: bold;
				color: #000;

				.name {
					margin-right: 14px;
				}
			}

			.area {
				margin-top: 4px;
				color: #999;
			}
		}
	}

	.input_area {
		padding: 10px 14px 5px;

		::v-deep .u-form-item__body__right__message {
			margin-left: 91px !important;
		}
	}

	.goods_detail_c {
		margin: 12px 0;
		padding: 0 14px 14px;
		background-color: #fff;
		border-radius: 10px;

		.title {
			padding: 10px 0;
			font-weight: bold;
			border-bottom: 1px solid #f6f6f6;
		}

		.goods_item {
			margin-top: 12px;
		}
	}

	.total_panel {
		padding: 12px 14px;
		background-color: #fff;
		border-radius: 10px;

		.list {
			display: flex;
			justify-content: space-between;

			.label {
				color: #666666;
			}

			.value {
				font-weight: bold;
			}

			.special {
				color: v-bind(secondaryColor);
			}
		}

		.list+.list {
			padding-top: 14px;
		}
	}

	.bar_bottom {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.left {
			flex: 1;

			.special {
				color: v-bind(secondaryColor);
				font-weight: 500;
			}

			.icon {
				font-size: 10px;
			}

			.num {
				font-size: 20px;
			}
		}

		.button {
			width: 200rpx;
			height: 70rpx;
			line-height: 70rpx;
			border-radius: 20px;
			background-color: v-bind(primaryColor);

			&.disabled {
				opacity: 0.5;
			}
		}
	}

	.choose_pay_methods {
		position: relative;
		border-radius: 20px 20px 0 0;
		background-color: #fff;
		text-align: center;

		.closeable {
			position: absolute;
			right: 14px;
			top: 10px;
		}

		.title {
			padding-top: 12px;
			padding-bottom: 20px;
			font-size: 16px;
			font-weight: bold;
		}

		.item {
			padding: 18px 0;
			border-bottom: 1px solid #f5f5f5;
		}

		.brace {
			height: 8px;
			background-color: #f5f5f5;
		}

		.cancel {
			padding: 20px 0;
			color: #666;
		}
	}

	.offlineVouchersPopupWrap {
		padding: 0 14px;

		.title {
			text-align: center;
			font-size: 16px;
			padding: 16px 0 10px;
			font-weight: bold
		}

		.uploadWrap {
			padding: 10px 0 28rpx;

			.tips {
				padding-bottom: 8px;
				color: #555;
			}
		}

		.button_c {
			padding: 10px 0px;
		}
	}
</style>
<style>
	/*只能在这里设置*/
	page {
		background-color: #f5f5f5;
	}
</style>